package com.lzhan.day17.reflectionconstructer;

import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

public class User {
	private String name;
	public int age;
	
	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}
	
	public User() {
		super();
		System.out.println("空构造函数");
	}

	public User(String name) {
		super();
		this.name = name;
		System.out.println("name is "+name);
	}
	public static class Test{
		public static void main(String[] args) {
			Class class1=User.class;
			try {
				User user1=(User) class1.getConstructor(new Class[]{}).newInstance(new Object[]{});
				User user2=(User) class1.getConstructor(new Class[]{String.class}).newInstance(new Object[]{"tom"});
				/*Method[] m1=class1.getMethods();
				for (Method method : m1) {
					System.out.println("method->"+method);
				}
				Method[] m2=class1.getDeclaredMethods();
				for (Method method : m2) {
					System.out.println("method****"+method);
				}*/
				
//				获取setName(String name) 方法
				
				Method m3=class1.getDeclaredMethod("setName", new Class[]{String.class});
				System.out.println(m3);
				m3.setAccessible(true);
				m3.invoke(user1, new Object[]{"helen"});
				
//				获取getName()方法
				
				Method m4=class1.getMethod("getName", new Class[]{});
				String s=(String) m4.invoke(user1, new Object[]{});
				System.out.println(s);
				
//				***************************************
//				获取自身及父类所有public Field
			
				Field[] fields1=class1.getFields();
				for (Field field : fields1) {
//					System.out.println(field);
				}
				
//				获取自身所有Field
				
				Field[] fields2=class1.getDeclaredFields();
				for (Field field : fields2) {
					System.out.println("User class method:"+field);
				}
				
//				获取age
				
				Field field_age=class1.getField("age");
				field_age.set(user2, 50);
				System.out.println("user2 age :"+field_age.get(user2));
				
			} catch (InstantiationException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IllegalAccessException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IllegalArgumentException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (InvocationTargetException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (NoSuchMethodException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (SecurityException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (NoSuchFieldException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}
}
